<template>
  <div>
    <a-modal v-model="visible" title="工单信息" width="50%">
      <template slot="footer" class="modelBtn">
        <a-button
          @click="visible = false"
          style="background: #d7d7d7; color: #fff; border: none"
          >取消</a-button
        >
        <a-button
          v-if="tabKey === '5' || modalFlag == 'add'"
          :loading="loading"
          type="primary"
          @click="onSubmit"
          >确定</a-button
        >
        <a-button
          v-if="tabKey === '15' && modalFlag != 'add'"
          :loading="loading"
          type="primary"
          @click="updateConfirm"
          >提交</a-button
        >
        <a-button
          v-if="tabKey === '45' && modalFlag != 'add'"
          :loading="loading"
          type="primary"
          @click="updateFinancial"
          >提交</a-button
        >

        <a-button
          v-if="state == 'finance' && tabKey != '35' && port != 'client'"
          :loading="loading"
          type="primary"
          @click="financiaLcomplete"
          >结算</a-button
        >
      </template>
      <h3>基本信息</h3>
      <a-form-model
        ref="ruleForm"
        :model="dto"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="客户编号" prop="tenantId">
              <span v-if="modalFlag === 'info'">
                {{ dto.tenantId }}
              </span>
              <a-select
                v-if="modalFlag != 'info'"
                v-model="dto.tenantId"
                show-search
                size="small"
                option-filter-prop="children"
                style="width: 100%"
                :filter-option="filterOption"
                @change="changeTenantId"
              >
                <a-select-option
                  :value="item.tenantId"
                  v-for="item in accArray"
                  :key="item.id"
                  :titles="item.title"
                >
                  {{ item.companyName + "/" + item.tenantId }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="工单仓库" prop="warehousingId">
              <span v-if="modalFlag === 'info'">
                {{ dto.warehousingName }}
              </span>
              <a-select
                v-if="modalFlag != 'info'"
                style="width: 100%"
                size="small"
                show-search
                option-filter-prop="children"
                :filter-option="filterOption"
                @change="handleChangeWarehouse"
                v-model="dto.warehousingName"
              >
                <a-select-option
                  :value="item.sysStoreHouseId"
                  v-for="item in warehouse"
                  :key="item.sysStoreHouseId"
                  :name="item.storeHouseCode"
                >
                  {{ item.storeHouseCode }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-model-item label="操作类型" prop="type">
              <span v-if="modalFlag === 'info'">
                {{ dto.typeName }}
              </span>
              <a-select
                v-if="modalFlag != 'info'"
                v-model="dto.type"
                show-search
                size="small"
                option-filter-prop="children"
                style="width: 100%"
                :filter-option="filterOption"
                @change="(value, option) => changeTypeId(option)"
              >
                <a-select-option
                  :value="item.key"
                  v-for="item in treatmentArray"
                  :key="item.key"
                  :titles="item.title"
                >
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="工单标题" prop="title">
              <a-input
              :maxLength="128"
                v-if="modalFlag != 'info'"
                style="width: 100%"
                size="small"
                v-model="dto.title"
              />
              <span v-if="modalFlag === 'info'">
                {{ dto.title }}
              </span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="modalFlag == 'info' ? 24 : 12">
            <a-form-model-item label="工单类型" prop="isUrgent">
              <a-select
                v-if="modalFlag != 'info'"
                style="width: 100%"
                size="small"
                v-model="dto.isUrgent"
              >
                <a-select-option value="0"> 普通 </a-select-option>
                <a-select-option value="1"> 加急 </a-select-option>
              </a-select>
              <div v-if="modalFlag === 'info'">
                {{ dto.isUrgent === "0" ? "普通" : "加急" }}
                <span v-if="dto.isUrgent == '1' " style="color: #f00;font-size:12px"> 【注：加急工单费用增加20%!】 </span>
              </div>
              <span
                v-if="dto.isUrgent == '1' && modalFlag != 'info'"
                style="color: #f00;font-size:12px"
                >注：加急工单费用增加20%!</span
              >
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item label="工单描述" prop="workDescribe">
              <span v-if="modalFlag === 'info'">
                {{ dto.workDescribe }}
              </span>
              <a-input
                v-if="modalFlag != 'info'"
                size="small"
                v-model="dto.workDescribe"
                type="textarea"
                :maxLength="256"
                :rows="4"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <h3>关联SKU</h3>
      <div class="add-commodity">
        <p style="padding-left: 1.5rem" v-if="modalFlag != 'info'">
          <span style="margin-right: 20px">
            <span style="color: red; margin: 0">*</span>SKU：<a-select
              placeholder="请选择SKU"
              size="small"
              show-search
              option-filter-prop="children"
              style="width: 15rem"
              :filter-option="filterOption"
              @change="changeAddSku"
              v-model="addTableObj.key"
            >
              <a-select-option
                :value="item.id"
                v-for="item in SKUchineseName"
                :key="item.id"
                :sku="item.sku"
                :skuname="item.skuName"
                :productTag="item.productTag"
                :remainingNumber="item.remainingNumber"
                :skuId="item.skuId"
                :warehousingId="item.warehousingId"
              >
                (库存:{{ item.remainingNumber }}) {{ item.sku }}
              </a-select-option>
            </a-select>
          </span>
          <span style="margin-right: 20px">
            <span style="color: red; margin: 0">*</span>
            商品数量：
            <a-input-number
              size="small"
              style="width: 200px"
              v-model="addTableObj.productNumber"
              :min="1"
              :max="remainingNumber * 1"
            />
          </span>
          <span>
            <a-button type="primary" size="small" @click="addSKUTable">
              添加
            </a-button>
          </span>
        </p>
        <a-table
          :columns="columns"
          :data-source="dto.productInfos"
          :pagination="false"
          bordered
          size="small"
        >
          <span
            slot="action"
            slot-scope="text, record"
            v-if="modalFlag != 'info'"
          >
            <a-popconfirm
              title="确认删除该条数据吗?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="delRows(record)"
            >
              <a href="javascript:;">删除</a>
            </a-popconfirm>
          </span>
        </a-table>
      </div>
      <h3 v-if="modalFlag != 'info'">工单文件</h3>
      <span
        style="color: red"
        v-if="fileList.length < 6 && modalFlag != 'info'"
      >
        注：支持PNG，JPG，PDF，JPEG文件最多上传6个！
      </span>
      <div style="margin-top: 20px">
        <a-upload
          class="upload-list-inline"
          :action="baseUrl + '/by-file/uploadFile'"
          :beforeUpload="beforeUploads"
          name="file"
          :file-list="fileList"
          :multiple="true"
          list-type="picture"
          :headers="headersRow"
          @change="(fileList) => handleChangeRow(fileList)"
          @preview="preview"
        >
          <a-button
            v-if="fileList.length < 6 && modalFlag != 'info'"
            style="
              background: #66b1ff;
              color: #fff;
              border: none;
              margin-left: 8px;
              margin-right: 20px;
            "
            size="small"
            type="primary"
          >
            <a-icon type="upload" /> 上传文件
          </a-button>
        </a-upload>
      </div>
      <div v-if="modalFlag === 'edit' || modalFlag === 'info'">
        <h3
          v-if="
            (modalFlag === 'edit' || modalFlag === 'info') &&
            this.rowFileArray.length >= 1
          "
          style="margin-top: 20px"
        >
          已保存文件
        </h3>
        <span
          v-if="modalFlag === 'edit' && this.rowFileArray.length >= 1"
          style="color: red"
          >注:重新上传则覆盖以下文件!</span
        >
        <p v-for="item in this.rowFileArray" :key="item">
          <a :href="item" target="_blank">{{ item }}</a>
        </p>
      </div>

      <a-button
        size="small"
        style="margin: 10px 0"
        v-if="tabKey != '5' && modalFlag != 'add'"
        type="primary"
        @click="goService"
        >{{
          dto.isServiceItem * 1 === 0 ? "服务项登记" : "服务项登记查看"
        }}</a-button
      >
    </a-modal>
    <OrderRerviceModal @workOrderUpdate="workOrderUpdate" />
    <ServiceModalReap @workOrderUpdate="workOrderUpdate" />
  </div>
</template>

<script>
import baseUrl from "@/utils/baseUrl";
import { removefile, getWhList } from "@/apis/common";
import {
  workOrder_workSku,
  workOrder_addWorkSku,
  workOrder_editWorkSku,
  workOrder_updateConfirm,
  workOrder_updateFinancial,
  workOrder_financiaLcomplete,
  workOrder_workInfo,
} from "@/apis/system/workOrder/workOrder";
import OrderRerviceModal from "./OrderRerviceModal";
import ServiceModalReap from "@/components/serviceModal/ServiceModalReap";
export default {
  components: {
    OrderRerviceModal,
    ServiceModalReap,
  },
  props: [
    "treatmentArray",
    "accArray",
    "getTabList",
    "tabKey",
    "state",
    "port",
  ],
  mounted() {
    this.$bus.$off("workOrder_workInfo");
    this.$bus.$on("workOrder_workInfo", async (record, flag) => {
      if (flag === "edit") {
        this.modalFlag = "edit";
      } else if (flag === "info") {
        this.modalFlag = "info";
      }
      let res = await workOrder_workInfo(record.id);
      if (res.code === "200") {
        this.dto = { ...res.responseBody };

        this.rowFileArray =
          this.dto.file === null ? [] : this.dto.file.split(",");
        this.fileList = [];
        this.fileArray = [];
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields();
        }
      }

      let { code, responseBody } = await workOrder_workSku(
        this.dto.warehousingId,
        this.dto.tenantId
      );
      if (code === "200") {
        this.SKUchineseName = responseBody;
        this.visible = true;
      }
    });
  },
  data() {
    return {
      //根据客户id查仓库
      warehouse: [],
      serviceVisible: false,
      rowFileArray: [],
      modalFlag: "",
      fileArray: [],
      baseUrl,
      fileList: [],
      loading: false,
      visible: false,
      //上传文件请求头
      headersRow: {
        authorization: "authorization-text",
        token: sessionStorage.getItem("tk"),
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
      dto: {
        warehousingId: null,
        warehousingName: null,
        workDescribe: null,
        type: null,
        typeName: null,
        title: null,
        file: null,
        isUrgent: null,
        productInfos: [
          // {
          //   sku: null,
          //   skuId: null,
          //   skuName: null,
          //   productNumber: null,
          //   productTag: null,
          // },
        ],
      },
      rules: {
        warehousingId: [
          {
            required: true,
            message: "请选择仓库！",
            trigger: "blur",
          },
        ],
        isUrgent: [
          {
            required: true,
            message: "请选择工单类型！",
            trigger: "blur",
          },
        ],
        type: [
          { required: true, message: "请选择操作类型！", trigger: "blur" },
        ],
        title: [{ required: true, message: "标题为必填项！", trigger: "blur" }],
        workDescribe: [
          {
            required: true,
            message: "请输入描述！",
            trigger: "blur",
          },
        ],
        tenantId: [
          {
            required: true,
            message: "请选择客户编号！",
            trigger: "blur",
          },
        ],
      },
      //sku列表
      SKUchineseName: [],
      // SKUid
      addTableObj: {
        //输入数量
        productNumber: 1,
        // SKU名称
        skuName: "",
        //   // SKU标签
        productTag: "",
        //   // sku
        sku: "",
        key: undefined,
        skuId: "",
      },
      //限制数量
      remainingNumber: "",
    };
  },
  methods: {
    //服务项操作后重新查询数据
    async workOrderUpdate() {
      this.modalFlag = "edit";
      let res = await workOrder_workInfo(this.dto.id);
      if (res.code === "200") {
        this.dto = res.responseBody;
      }
    },
    //打开服务项
    goService() {
      if (this.dto.isServiceItem < 1 && this.dto.workState == "15") {
        this.$bus.$emit("serviceRegistration", true, this.dto);
      } else if (this.dto.isServiceItem >= 1 && this.dto.workState == "15") {
        this.$bus.$emit(
          "reappearance",
          this.dto,
          6,
          this.dto.id,
          true,
          "warehouse"
        );
      } else if (
        (this.dto.workState != "15" && sessionStorage.getItem("terminal")) ===
          "1" &&
        (this.dto.workState == "45" || this.dto.workState === "25")
      ) {
        this.$bus.$emit("reappearance", this.dto, 6, this.dto.id, true);
      } else {
        this.$bus.$emit("reappearance", this.dto, 6, this.dto.id, false);
      }
    },
    //客户ID查询仓库
    async changeTenantId(value) {
      let { code, responseBody } = await getWhList(value);
      if (code === "200") {
        this.warehouse = responseBody.filter((item) => {
          return item.warehouseId != null;
        });
      }
      this.dto.productInfos = [];
      this.dto.warehousingId = null;
      this.dto.warehousingName = null;
      this.addTableObj = {
        //输入数量
        productNumber: 1,
        // SKU名称
        skuName: "",
        //   // SKU标签
        productTag: "",
        //   // sku
        sku: "",
        key: undefined,
        skuId: "",
      };
    },
    //仓库提交到客服再次确认
    updateConfirm() {
      this.loading = true;
      setTimeout(async () => {
        let { code } = await workOrder_updateConfirm(this.dto.id);
        if (code === "10000") {
          this.loading = false;
          this.visible = false;
          this.getTabList();
        }
      }, 1000);
    },
    //财务结算到已完成
    financiaLcomplete() {
      this.loading = true;
      setTimeout(async () => {
        let { code, message } = await workOrder_financiaLcomplete(this.dto.id);
        if (code === "10000") {
          this.loading = false;
          this.visible = false;
          this.getTabList();
        } else {
          this.$message.error(message);
          this.loading = false;
        }
      }, 1000);
    },
    //客服再次确认到财务
    updateFinancial() {
      this.loading = true;
      setTimeout(async () => {
        let { code } = await workOrder_updateFinancial(this.dto.id);
        if (code === "10000") {
          this.loading = false;
          this.visible = false;
          this.getTabList();
        }
      }, 1000);
    },
    //退件处理改变
    changeTypeId(option) {
      this.dto.typeName = option.data.attrs.titles;
    },
    //图片点击查看
    preview(file) {
      window.open(file.response.responseBody[0]);
    },
    // 出库仓库更改
    async handleChangeWarehouse(value, option) {
      let { code, responseBody } = await workOrder_workSku(
        value,
        this.dto.tenantId
      );
      if (code === "200") {
        this.SKUchineseName = responseBody;
      }
      this.dto.productInfos = [];
      this.addTableObj = {
        //输入数量
        productNumber: 1,
        // SKU名称
        skuName: "",
        //   // SKU标签
        productTag: "",
        //   // sku
        sku: "",
        key: undefined,
        skuId: "",
      };
      this.dto.warehousingName = option.data.attrs.name;
      this.dto.warehousingId = value;
    },
    //每一行上传文件
    async handleChangeRow(info) {
      this.fileList = info.fileList;
      if (info.file.status === "done") {
        this.$message.success(`${info.file.name} 上传成功`);
        this.fileArray.push(info.file.response.responseBody[0]);
        this.dto.file = this.fileArray.join(",");
      } else if (info.file.status === "removed") {
        let res = await removefile(info.file.response.responseBody);
        res;
      }
    },
    // 限制上传文件
    beforeUploads(file) {
      return new Promise((resolve, reject) => {
        this.files = file;
        const isLt6M = file.size / 1024 / 1024 < 6;
        const pdf = file.type === "application/pdf";
        const img =
          file.type === "image/jpeg" ||
          file.type === "image/png" ||
          file.type === "image/jpg";
        if (!pdf && !img) {
          this.$message.error("上传文件只能是 png、jpeg、jpg、PDF!");
          return reject(false);
        }
        if (!isLt6M) {
          this.$message.error("文件大小限制小于6MB!");
          return reject(false);
        }
        return resolve(true);
      });
    },
    //添加数据到表格
    addSKUTable() {
      this.skuFlag = true;
      if (this.addTableObj.sku === null || this.addTableObj.sku === "") {
        this.$message.error("请选择SKU！");
        return false;
      }
      this.dto.productInfos.forEach((item) => {
        if (item.sku === this.addTableObj.sku) {
          this.skuFlag = false;
        }
      });
      if (this.skuFlag) {
        let obj = { ...this.addTableObj };
        this.dto.productInfos.push(obj);
        this.addTableObj.productNumber = 1;
      } else {
        this.$message.error("无法添加相同SKU，请直接删除更改数量！");
        return false;
      }

      // if (
      //   this.selectionRowsPlus.length >= 1 &&
      //   this.OutboundModalData.recordList.length === 0
      // ) {
      //   this.OutboundModalData.recordList.push({
      //     skuName: this.addTableObj.skuName,
      //     sku: this.addTableObj.sku,
      //     productTag: this.addTableObj.productTag,
      //     inputNumber: this.addTableObj.inputNumber,
      //     productId: this.addTableObj.key,
      //     skuId: this.addTableObj.skuId,
      //     prList: this.addTableObj.prList,
      //     warehousingId: this.addTableObj.warehousingId,
      //   });
      // } else {
      //   if (this.OutboundModalData.recordList.length >= 1) {
      //     this.OutboundModalData.recordList.forEach((item, i) => {
      //       if (item.sku === this.addTableObj.sku) {
      //         this.OutboundModalData.recordList.splice(i, 1);
      //       }
      //     });
      //     this.OutboundModalData.recordList.push({
      //       skuName: this.addTableObj.skuName,
      //       sku: this.addTableObj.sku,
      //       productTag: this.addTableObj.productTag,
      //       inputNumber: this.addTableObj.inputNumber,
      //       productId: this.addTableObj.key,
      //       skuId: this.addTableObj.skuId,
      //       prList: this.addTableObj.prList,
      //       warehousingId: this.addTableObj.warehousingId,
      //     });
      //   }
      // }

      // this.addTableObj.inputNumber = 0;
      // this.selectionRowsPlus = [];
      // this.selectedRowKeys = [];
    },
    //删除SKU
    delRows(record) {
      this.dto.productInfos = this.dto.productInfos.filter((item) => {
        return item.sku != record.sku;
      });
    },
    // SKU下拉框
    changeAddSku(value, option) {
      this.remainingNumber = option.data.attrs.remainingNumber;
      this.addTableObj.skuName = option.data.attrs.skuname;
      this.addTableObj.sku = option.data.attrs.sku;
      this.addTableObj.skuId = option.data.attrs.skuId;
      this.addTableObj.productTag = option.data.attrs.productTag;
      // this.addTableObj.id = value;
      this.addTableObj.key = value;
    },
    // 显示新增模态框
    shwoModal() {
      this.visible = true;
      this.dto = {
        warehousingId: null,
        warehousingName: null,
        workDescribe: null,
        type: null,
        typeName: null,
        title: null,
        file: null,
        isUrgent: null,
        productInfos: [],
      };
      this.fileList = [];
      this.modalFlag = "add";
      this.fileArray = [];
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields();
      }
    },
    // 新增工单
    onSubmit() {
      this.loading = true;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.dto.productInfos.length <= 0) {
            this.$message.error("请添加SKU!");
            this.loading = false;
            return false;
          }
          if (this.modalFlag === "add") {
            setTimeout(async () => {
              let { code } = await workOrder_addWorkSku(this.dto);
              if (code === "10000") {
                this.loading = false;
                this.visible = false;
                this.getTabList();
              } else {
                this.loading = false;
              }
            }, 1000);
          } else if (this.modalFlag === "edit") {
            setTimeout(async () => {
              let { code } = await workOrder_editWorkSku(this.dto);
              if (code === "10000") {
                this.loading = false;
                this.visible = false;
                this.getTabList();
              } else {
                this.loading = false;
              }
            }, 1000);
          }
        } else {
          this.$message.error("请检查必填项!");
          this.loading = false;
          return false;
        }
      });
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },

  computed: {
    columns() {
      return [
        {
          title: "商品名称",
          dataIndex: "skuName",
          align: "center",
          // scopedSlots: { customRender: "selfClassifyName" },
          ellipsis: true,
          width: "20%",
        },
        {
          title: "SKU",
          dataIndex: "sku",
          align: "center",
          width: "20%",
          ellipsis: true,
          scopedSlots: { customRender: "sku" },
        },
        {
          title: "标签",
          dataIndex: "productTag",
          scopedSlots: { customRender: "productTag" },
          align: "center",
          width: "20%",
          ellipsis: true,
        },
        {
          title: "数量",
          dataIndex: "productNumber",
          scopedSlots: { customRender: "productNumber" },
          align: "center",
          width: "20%",
          ellipsis: true,
        },
        {
          title: "操作",
          dataIndex: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
          width: 120,
        },
      ];
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.ant-upload-list-picture .ant-upload-list-item,
.ant-upload-list-picture-card .ant-upload-list-item {
  float: left;
  width: 200px;
  margin-right: 8px;
}
/deep/.ant-modal-footer {
  text-align: center !important;
  button {
    margin: 0 50px;
  }
}
/deep/.ant-col-8 {
  width: auto;
}
</style>
